import express from "express";
import { ObjectId } from "mongodb";
import authMiddleware from "../middleware/auth.js";
import { getDb } from "../config/database.js";

const router = express.Router();
const COLLECTION = "networks";

// 获取网点列表
router.get("/", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const { page = 1, limit = 10, search = "", status = "" } = req.query;
    const skip = (Number(page) - 1) * Number(limit);

    // 构建查询条件
    const query = {};

    if (search) {
      query.$or = [
        { networkName: { $regex: search, $options: "i" } },
        { networkCode: { $regex: search, $options: "i" } },
        { managerName: { $regex: search, $options: "i" } },
        { managerAlias: { $regex: search, $options: "i" } },
      ];
    }

    if (status) {
      query.status = status;
    }

    // 查询数据
    const networks = await db
      .collection(COLLECTION)
      .find(query)
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(Number(limit))
      .toArray();

    // 获取总数
    const total = await db.collection(COLLECTION).countDocuments(query);

    res.json({
      networks,
      total,
      page: Number(page),
      limit: Number(limit),
      totalPages: Math.ceil(total / Number(limit)),
    });
  } catch (error) {
    console.error("获取网点列表失败:", error);
    res.status(500).json({ error: "获取网点列表失败" });
  }
});

// 创建网点
router.post("/", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const {
      networkName,
      networkCode,
      address,
      managerName,
      managerAlias,
      contactPhone,
      wechat,
      prepaidAmount,
      transactionMethods,
      status,
    } = req.body;

    // 验证必填字段
    if (
      !networkName ||
      !networkCode ||
      !address ||
      !managerName ||
      !contactPhone ||
      prepaidAmount === undefined
    ) {
      return res.status(400).json({
        error:
          "网点名称、编码、地址、负责人姓名、联系方式和面单预充金额为必填项",
      });
    }

    // 检查网点编码是否已存在
    const existingNetwork = await db
      .collection(COLLECTION)
      .findOne({ networkCode });

    if (existingNetwork) {
      return res.status(400).json({
        error: `网点编码"${networkCode}"已存在，请使用其他编码`,
      });
    }

    // 创建新网点
    const newNetwork = {
      networkName,
      networkCode,
      address,
      managerName,
      managerAlias: managerAlias || "",
      contactPhone,
      wechat: wechat || "",
      prepaidAmount: Number(prepaidAmount) || 0,
      transactionMethods: transactionMethods || [],
      status: status || "active",
      createdAt: new Date(),
      updatedAt: new Date(),
    };

    const result = await db.collection(COLLECTION).insertOne(newNetwork);
    newNetwork._id = result.insertedId;

    res.status(201).json(newNetwork);
  } catch (error) {
    console.error("创建网点失败:", error);

    // 处理唯一索引冲突错误
    if (error.code === 11000) {
      return res.status(400).json({
        error: `网点编码"${req.body.networkCode}"已存在，请使用其他编码`,
      });
    }

    res.status(500).json({ error: "创建网点失败" });
  }
});

// 更新网点
router.put("/:id", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const { id } = req.params;
    const {
      networkName,
      networkCode,
      address,
      managerName,
      managerAlias,
      contactPhone,
      wechat,
      prepaidAmount,
      transactionMethods,
      status,
    } = req.body;

    // 验证必填字段
    if (
      !networkName ||
      !networkCode ||
      !address ||
      !managerName ||
      !contactPhone ||
      prepaidAmount === undefined
    ) {
      return res.status(400).json({
        error:
          "网点名称、编码、地址、负责人姓名、联系方式和面单预充金额为必填项",
      });
    }

    // 检查网点编码是否已被其他网点使用
    const existingNetwork = await db.collection(COLLECTION).findOne({
      networkCode,
      _id: { $ne: new ObjectId(id) },
    });

    if (existingNetwork) {
      return res.status(400).json({
        error: `网点编码"${networkCode}"已被其他网点使用`,
      });
    }

    // 更新网点
    const updateData = {
      $set: {
        networkName,
        networkCode,
        address,
        managerName,
        managerAlias: managerAlias || "",
        contactPhone,
        wechat: wechat || "",
        prepaidAmount: Number(prepaidAmount) || 0,
        transactionMethods: transactionMethods || [],
        status: status || "active",
        updatedAt: new Date(),
      },
    };

    const result = await db
      .collection(COLLECTION)
      .findOneAndUpdate({ _id: new ObjectId(id) }, updateData, {
        returnDocument: "after",
      });

    if (!result) {
      return res.status(404).json({ error: "网点不存在" });
    }

    res.json(result);
  } catch (error) {
    console.error("更新网点失败:", error);

    // 处理唯一索引冲突错误
    if (error.code === 11000) {
      return res.status(400).json({
        error: `网点编码"${req.body.networkCode}"已被其他网点使用`,
      });
    }

    res.status(500).json({ error: "更新网点失败" });
  }
});

// 获取单个网点
router.get("/:id", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const network = await db
      .collection(COLLECTION)
      .findOne({ _id: new ObjectId(req.params.id) });

    if (!network) {
      return res.status(404).json({ error: "网点不存在" });
    }

    res.json(network);
  } catch (error) {
    console.error("获取网点失败:", error);
    res.status(500).json({ error: "获取网点失败" });
  }
});

// 删除网点
router.delete("/:id", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const result = await db
      .collection(COLLECTION)
      .findOneAndDelete({ _id: new ObjectId(req.params.id) });

    if (!result) {
      return res.status(404).json({ error: "网点不存在" });
    }

    res.json({ message: "网点删除成功" });
  } catch (error) {
    console.error("删除网点失败:", error);
    res.status(500).json({ error: "删除网点失败" });
  }
});

export default router;
